package com.tjbklx1.redis.chap05;

import java.util.Date;
import java.util.List;
import java.util.Set;

import com.tjbklx1.redis.JedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple;

public class App52_Log {

	public static void main(String[] args) {
		Jedis conn = JedisUtil.getJedisWithDB();
		new App52_Log().testLogCommon(conn);
	}

	public void testLogCommon(Jedis conn) {
		System.out.println("\n----- testLogCommon -----");
		System.out.println("Let's write some items to the common log");
		for (int count = 1; count < 6; count++) {
			for (int i = 0; i < count; i++) {
				logCommon(conn, "test", "message-" + count);
			}
		}
		Set<Tuple> common = conn.zrevrangeWithScores("common:test:info", 0, -1);
		System.out.println("The current number of common messages is: " + common.size());
		System.out.println("Those common messages are:");
		for (Tuple tuple : common) {
			System.out.println("  " + tuple.getElement() + ", " + tuple.getScore());
		}
		assert common.size() >= 5;
	}

	public void logCommon(Jedis conn, String name, String message) {
		logCommon(conn, name, message, MyLogger.INFO, 5000); // INFO方式 写日志
	}

	/**
	 * 普通的方式写日志 (事务的方式 Transaction )
	 * @param conn
	 * @param name 日志的名字
	 * @param message 日志的内容
	 * @param severity 日志的级别
	 * @param timeout 超时时间
	 */
	public void logCommon(Jedis conn, String name, String message, String severity, int timeout) {
		String commonDest = "common:" + name + ':' + severity;
		String startKey = commonDest + ":start";
		long end = System.currentTimeMillis() + timeout;
		while (System.currentTimeMillis() < end) {  // 在超时时间范围内 反复的写日志
			conn.watch(startKey);
			String hourStart = MyLogger.ISO_FORMAT.format(new Date()); //
			String existing = conn.get(startKey);

			Transaction trans = conn.multi();
			if (existing != null && MyLogger.COLLATOR.compare(existing, hourStart) < 0) {
				trans.rename(commonDest, commonDest + ":last");
				trans.rename(startKey, commonDest + ":pstart");
				trans.set(startKey, hourStart);
			}

			trans.zincrby(commonDest, 1, message);

			String recentDest = "recent:" + name + ':' + severity;
			trans.lpush(recentDest, MyLogger.TIMESTAMP.format(new Date()) + ' ' + message);
			trans.ltrim(recentDest, 0, 99);
			List<Object> results = trans.exec();
			if (results == null) {
				continue;
			}
			return;
		}
	}
}
